# -*- coding:utf-8 -*-
"""
书籍属性与方法
"""
import datetime
import hashlib
import random
import re
import string

class Book:
    """
    @ClassName：Book
    @Description： 图书实体类，映射数据库一条图书数据
    负责属性赋值检查，自动产生唯一 ID
    @Author：锦沐Python

    参数:
    book_id (str): 书籍的 ID
    book_name (str): 书籍的标题
    ISBN (str): 国际标准书号
    record_time (str): 书籍的入库时间
    category (str): 书籍的类别
    author (str): 书籍的作者
    publisher (str): 书籍的出版商
    publication_date (str): 书籍的出版日期
    borrowed_by (str): 借书的人（如果已被借）
    borrow_time (str): 借书的时间（如果已被借）
    loan_period (int): 借阅期限（以天为单位）
    due_time (str): 应还书的时间（如果已被借）

    """

    def __init__(self, book_id="default", book_name="default", ISBN="default",
                 record_time="default", category="default", author="default",
                 publisher="default", publication_date="default", borrowed_by="",
                 borrow_time="", loan_period=15, due_time="", img_url=""):

        self._book_id = str(book_id)
        self._book_name = str(book_name)
        self._ISBN = str(ISBN)
        self._record_time = str(record_time)
        self._category = str(category)
        self._author = str(author)
        self._publisher = str(publisher)
        self._publication_date = str(publication_date)
        self._borrowed_by = str(borrowed_by)
        self._borrow_time = str(borrow_time)
        self._loan_period = int(loan_period)
        self._due_time = str(due_time)
        self._img_url = str(img_url)
        # print(self.obj_to_dict())

    @property
    def book_id(self):
        return self._book_id

    @book_id.setter
    def book_id(self, book_id):
        if isinstance(book_id, str) and len(book_id) > 0:
            self._book_id = book_id
        else:
            raise ValueError("book_id 必须长度大于0")

    @property
    def book_name(self):
        return self._book_name

    @book_name.setter
    def book_name(self, book_name):
        if isinstance(book_name, str) and book_name != "":
            self._book_name = book_name
        else:
            raise ValueError("book_name 必须是字符串，且长度不为0")

    @property
    def ISBN(self):
        return self._ISBN

    @ISBN.setter
    def ISBN(self, ISBN):
        if isinstance(ISBN, str) and ISBN != "":
            self._ISBN = ISBN
        else:
            raise ValueError("ISBN 必须是字符串，且长度不为0")

    @property
    def record_time(self):
        return self._record_time

    @record_time.setter
    def record_time(self, record_time):
        time_pattern = r'^\d{4}\.\d{2}\.\d{2} \d{2}:\d{2}:\d{2}$'

        if not isinstance(record_time, str):
            raise ValueError("record_time 时间格式为 2024.07.03 12:23:23")

        if re.match(time_pattern, record_time):
            self._record_time = record_time
        else:
            self._record_time = ""

    @property
    def category(self):
        return self._category

    @category.setter
    def category(self, category):
        if isinstance(category, str) and category != "":
            self._category = category
        else:
            raise ValueError("category 必须是字符串,且长度不为0")

    @property
    def author(self):
        return self._author

    @author.setter
    def author(self, author):
        if isinstance(author, str) and len(author) > 3:
            self._author = author
        else:
            raise ValueError("author 必须是大于3位的字符串")

    @property
    def publisher(self):
        return self._publisher

    @publisher.setter
    def publisher(self, publisher):
        if isinstance(publisher, str) and publisher != "":
            self._publisher = publisher
        else:
            raise ValueError("publisher 必须是字符串，且长度不为0")

    @property
    def publication_date(self):
        return self._publication_date

    @publication_date.setter
    def publication_date(self, publication_date):
        time_pattern = r'^\d{4}.\d{2}$'
        if isinstance(publication_date, str) and re.match(time_pattern, publication_date):
            self._publication_date = publication_date
        else:
            raise ValueError("publication_date 时间格式为 2024.07")

    @property
    def borrowed_by(self):
        return self._borrowed_by

    @borrowed_by.setter
    def borrowed_by(self, student_id):
        if isinstance(student_id, str):
            self._borrowed_by = student_id
        else:
            raise ValueError("borrowed_by : student_id 必须是字符串")

    @property
    def borrow_time(self):
        return self._borrow_time

    @borrow_time.setter
    def borrow_time(self, borrow_time):
        time_pattern = r'^\d{4}\.\d{2}\.\d{2} \d{2}:\d{2}:\d{2}$'
        if not isinstance(borrow_time, str):
            raise ValueError("borrow_time必须是一个字符串，且格式为 2024.07.03 12:23:23")

        if re.match(time_pattern, borrow_time):
            self._borrow_time = borrow_time
        else:
            self._borrow_time = ""

    @property
    def loan_period(self):
        return self._loan_period

    @loan_period.setter
    def loan_period(self, loan_period):
        if isinstance(loan_period, int):
            self._loan_period = loan_period
        else:
            raise ValueError("loan_period 必须是 int ")

    @property
    def due_time(self):
        return self._due_time

    @due_time.setter
    def due_time(self, due_time):
        time_pattern = r'^\d{4}\.\d{2}\.\d{2} \d{2}:\d{2}:\d{2}$'
        if not isinstance(due_time, str):
            raise ValueError("record_time 时间格式为  2024.07.03 12:12:12")

        if re.match(time_pattern, due_time):
            self._due_time = due_time
        else:
            self._due_time = ""

    def calculate_due_time(self):
        if self._borrow_time:
            borrow_datetime = datetime.datetime.strptime(self._borrow_time, "%Y.%m.%d %H:%M:%S")
            due_datetime = borrow_datetime + datetime.timedelta(days=self._loan_period)
            return due_datetime.strftime("%Y.%m.%d %H:%M:%S")

    @property
    def img_url(self):
        return self._img_url

    @img_url.setter
    def img_url(self, img_url):
        if isinstance(img_url, str):
            self._img_url = img_url
        else:
            raise ValueError("img_url 必须是字符串")

    def create_id(self, length=8):
        """
        生成唯一Id
        :param length:
        :return:
        """
        random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=5))
        unique_id = hashlib.md5(random_string.encode()).hexdigest()
        self.book_id = unique_id  # Store the generated ID if needed
        print(f"Generated ID: {unique_id}")
        return unique_id[:length]

    def obj_to_dict(self):
        # 复制__dict__以避免直接修改实例的属性字典
        book_dict = self.__dict__.copy()
        # 过滤掉不需要序列化的属性（例如，以__开头的Python特殊属性）
        filtered_dict = {k[1:] if k.startswith('_') else k: v for k, v in book_dict.items() if not k.startswith('__')}
        return filtered_dict
